#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUF_SIZE 100

void copy(char *src, char *dest, long start, long end);

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("请输入要拷贝的文件名, 及目标文件文名.\n");
        return -1;
    }

    
    fseek(fp_src, 0, SEEK_END);
    long file_size = ftell(fp_src);
    printf("file_size=%ld\n", file_size);

    pid_t pid = fork();

    // 子进程开始复制前一半
    if (pid == 0) {
        copy(fp_src, fp_dest, 0, file_size / 2);
    } else {
    // 父进程开始复制后一半
        copy(fp_src, fp_dest, file_size / 2, file_size);
        waitpid(pid, NULL, 0);
    }


    printf("copy done.\n");

    return 0;
}


void copy(char *src, char *dest, long start, long end)
{
    FILE * fp_src = fopen(src, "rb");

    if (NULL == fp_src) {
        perror("fopen src");
        return -1;
    }

    FILE * fp_dest = fopen(dest, "wb+");

    if (NULL == fp_dest) {
        perror("fopen dest");
        return -1;
    }


    fseek(src, 0 + start, SEEK_SET);
    fseek(dest, 0 + start, SEEK_SET);
    char buf[BUF_SIZE] = {0};
    size_t res;
    long cur;
    size_t size = sizeof(buf);


    do {
        res = fread(buf, 1, size, src);
        cur = ftell(src);

        if (res == 0) {
            if (feof(src)) {
                perror("fread src");
                return ;
            }
        }

        if (cur > end) {
            fwrite(buf, 1, res - (cur - end), dest);
        } else {
            fwrite(buf, 1, res, dest);
        }

    } while (cur <= end);

    if (EOF == fclose(fp_src)) {
        perror("fclose src");
        return -1;
    }

    if (EOF == fclose(fp_dest)) {
        perror("fclose dest");
        return -1;
    }



}



